#!/usr/bin/evn python
#! -*- coding: utf8 -*-
from django.core.exceptions import ValidationError
from django import forms
from django.forms.models import inlineformset_factory
from contacts.models import (Contact, Address)

class ContactForm(forms.ModelForm):
    class Meta:
        model = Contact
        exclude = ('owner', )
    confirm_email = forms.EmailField()

    def __init__(self, *args, **kwargs):
        if kwargs.get('instance'):
            email = kwargs['instance'].email
            kwargs.setdefault('initial', {})['confirm_email'] = email
        return super(ContactForm, self).__init__(*args, **kwargs)

    def clean(self):
        ''' valid form '''
        cdata = self.cleaned_data
        if cdata.get('email') != cdata.get('confirm_email'):
            raise ValidationError('email mismatch')
        return cdata

ContactAddressFormset = inlineformset_factory(Contact, Address)
